package com.ycy.chuwenuniapp.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycy.chuwenuniapp.common.ResCodeEnum;
import com.ycy.chuwenuniapp.common.ResData;
import com.ycy.chuwenuniapp.dto.GoodsTypeDto;
import com.ycy.chuwenuniapp.entity.GoodsSize;
import com.ycy.chuwenuniapp.entity.GoodsType;
import com.ycy.chuwenuniapp.exception.CustomException;
import com.ycy.chuwenuniapp.mapper.IGoodsTypeMapper;
import com.ycy.chuwenuniapp.vo.GoodsTypeVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GoodsTypeService extends ServiceImpl<IGoodsTypeMapper, GoodsType> {
    //增加或修改
    public ResData<Boolean> saveGoodsType(GoodsTypeDto dto) {
        String name = dto.getName();
        if(StrUtil.isBlank(name)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"缺失商品类型名");
        QueryWrapper<GoodsType> wrapper = new QueryWrapper<>();
        wrapper.eq("name",name);
        long sameNameCount = count(wrapper);
        if(sameNameCount != 0) throw new CustomException(ResCodeEnum.BAD_REQUEST,"已存在相同的商品类型名: " + name);

        GoodsType entity = new GoodsType();
        BeanUtil.copyProperties(dto,entity);
        boolean isSave = saveOrUpdate(entity);
        if(isSave) return ResData.success(true,"保存成功");
        else return ResData.fail(false,"服务器错误,保存商品类型失败");
    }

    //查全部
    public ResData<List<GoodsTypeVo>> findAll(String name) {
        QueryWrapper<GoodsType> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(name),"name",name);
        ArrayList<GoodsTypeVo> voList = new ArrayList<>();
        list(wrapper).forEach(item -> {
            GoodsTypeVo vo = new GoodsTypeVo();
            BeanUtil.copyProperties(item,vo);
            voList.add(vo);
        });
        return ResData.success(voList,"查询成功");
    }

    public ResData<Boolean> delete(String id) {
        if(StrUtil.isBlank(id)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"缺失商品类型id");
        boolean isRemove = removeById(id);
        if(isRemove) return ResData.success(true,"删除成功");
        else return ResData.fail(false,"不存在该id的商品类型或服务器错误");
    }
}
